<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit" :maskClosable="false">
    <BasicForm @register="registerForm" />
    <template #centerFooter>
      <a-button @click="handleSubmit(true)" :loading="btnLoading">测试连接</a-button>
    </template>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema } from './config';
  import * as _API from './api';
  import { message } from 'ant-design-vue';

  export default defineComponent({
    name: 'DataSourceModal',
    components: { BasicModal, BasicForm },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(false);
      const btnLoading = ref(false);

      const [registerForm, { resetFields, setFieldsValue, validate, setProps, getFieldsValue }] = useForm({
        labelWidth: 100,
        schemas: formSchema(isUpdate.value),
        showActionButtonGroup: false,
      });

      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        await resetFields();
        setModalProps({
          confirmLoading: false,
        });
        isUpdate.value = !!data?.isUpdate;
        await setProps({
          schemas: formSchema(isUpdate.value),
        });
        if (unref(isUpdate)) {
          await setFieldsValue({
            ...data.record,
          });
        }
      });

      const getTitle = computed(() => (!unref(isUpdate) ? '新增数据源' : '编辑数据源'));
      async function handleSubmit(isTest: boolean = false) {
        // 测试链接
        const connectMysql = (values): void => {
          btnLoading.value = true;
          _API.testAPI(values).then((res: any) => {
            const { code } = res.data;
            if (code !== 200) {
              message.error(res.data.message || '连接失败！');
            } else {
              message.success('连接成功！');
            }
            setTimeout(() => (btnLoading.value = false), 1000);
          });
        };
        if (isTest == true) return connectMysql(getFieldsValue());
        try {
          const values = await validate();
          setModalProps({ confirmLoading: true });
          if (!isUpdate.value) {
            // 新增
            await _API.addAPI(values);
          } else {
            // 编辑
            await _API.editAPI(getFieldsValue());
          }
          closeModal();
          emit('success');
        } finally {
          setTimeout(() => (btnLoading.value = false), 5000);
          setModalProps({ confirmLoading: false });
        }
      }

      return { registerModal, registerForm, getTitle, handleSubmit, btnLoading };
    },
  });
</script>
